package com.voice.server.command.impl;

import com.voice.server.entity.Device;
import com.voice.server.enums.DeviceStatusEnum;
import com.voice.server.message.sdk.DeviceTextMessage;
import com.voice.server.repository.DeviceRepository;
import com.wangjiacai.utils.utils.PingYinUtil;
import com.wangjiacai.utils.web.service.RedisService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component("textMatch")
public class MatchTextCommand extends TextCommand implements InitializingBean {

    public static String hashKey="matchText";

    @Autowired
    private RedisService redisService;
    @Autowired
    private DeviceRepository deviceRepository;

    @Override
    public void afterPropertiesSet() {
        List<Device> list=deviceRepository.findByStatus(DeviceStatusEnum.Online.getCode());
        list.stream().forEach(device -> redisService.hashSet(hashKey,device.getDeviceKey(),device.getMatchText()));
    }

    private boolean checkMatch(String deviceKey, String text) {
        String matchText=redisService.hashGet(hashKey,deviceKey);
        if(matchText==null) return false;
        String matchTextPinYin=PingYinUtil.getPingYinWithTone(matchText);
        if(matchTextPinYin==null) return false;
        String textTextPinYin=PingYinUtil.getPingYinWithTone(text);
        if(textTextPinYin==null) return false;
        if(!textTextPinYin.equals(matchTextPinYin)) return false;
        return true;
    }


    @Override
    public void executeSdk(String userId, String deviceKey, DeviceTextMessage deviceTextMessage) {
        if(!checkMatch(deviceKey,deviceTextMessage.getText()))return;
        super.executeSdk(userId, deviceKey, deviceTextMessage);
    }

    @Override
    public void executeApi(String userId, String deviceKey, DeviceTextMessage deviceTextMessage) {
        if(!checkMatch(deviceKey,deviceTextMessage.getText()))return;
        super.executeApi(userId, deviceKey, deviceTextMessage);
    }


}
